var imgs = document.getElementById('imgs');
var sideBar = document.getElementById('side-bar');

/* 存放img的DOM */
var imgArr = [];
/* 存放sidebar的DOM */
var barArr = [];

/* 记录active的img */
var activeImg = null;
/* 记录active的bar */
var activeBar = null;

data.forEach((ele, index) => {
    var pic = document.createElement('a');
    // pic.style.display = "block";
    pic.style.backgroundImage = `url(${ele.img})`;
    pic.setAttribute('href', "#");
    pic.style.backgroundColor = ele.bg;
    imgs.appendChild(pic)
    imgArr.push(pic);

    var barList = document.createElement('a');
    barList.className = "nav";
    barList.title = ele.title + " : " + ele.desc;
    barList.href = "#";
    barList.innerHTML = `<span>${ele.title}</span>${ele.desc}`
    sideBar.appendChild(barList)
    barArr.push(barList);

    /* 默认active为第一张 */
    if (index == 0) {
        pic.setAttribute('class', 'active');
        barList.setAttribute('class', 'active');
        activeBar = barList;
        activeImg = pic;
    }

    barList.onmouseenter = function () {
        /* 鼠标移入清楚定时器 */
        clearInterval(timer);
        /* 1. 将其他标签的active移除（img和bar的）*/
        activeBar.setAttribute('class', 'nav');
        activeImg.setAttribute('class', '');
        /* 2.给自身添加active（img和bar） */
        pic.setAttribute('class', 'active');
        barList.setAttribute('class', 'active');
        activeBar = barList;
        activeImg = pic;
    }
    barList.onmouseleave = function () {
        timer = setInterval(move, 1200)
    }
})

var timer = setInterval(move, 1200);

function move() {
    /* 1.将当前avtive移除  */
    activeBar.setAttribute('class', 'nav');
    activeImg.setAttribute('class', '');
    /* 2.给下一个元素添加active */
    var i = imgArr.indexOf(activeImg); //active的元素所在位置
    if (i == imgArr.length - 1) {
        //最后一个元素，编导第一个
        activeImg = imgArr[0];
        activeBar = barArr[0];
    } else {
        /* 记录最新active元素 */
        activeBar = barArr[i + 1];
        activeImg = imgArr[i + 1];
    }
    /* 给激活元素添加active */
    activeBar.setAttribute('class', 'active');
    activeImg.setAttribute('class', 'active')

}